##
#   Project: BlueDUN
#            Internet connection manager for bluetooth devices.
#    Author: Fabio Castelli <muflone@vbsimple.net>
# Copyright: 2009 Fabio Castelli
#   License: GPL-2+
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the Free
#  Software Foundation; either version 2 of the License, or (at your option)
#  any later version.
# 
#  This program is distributed in the hope that it will be useful, but WITHOUT
#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#  more details.
# 
# On Debian GNU/Linux systems, the full text of the GNU General Public License
# can be found in the file /usr/share/common-licenses/GPL-2.
##

import gtk
import gtk.glade
import glib
import handlepaths
import subprocess
import os.path
import settings
import gobject
import gettext
from gettext import gettext as _

txtbLog = None
btnConnect = None
imgStatus = None
procDial = None
connection = None
lblConnection2 = None
lblInterface2 = None
lblLocalIP2 = None
lblRemoteIP2 = None
lblDNS12 = None
lblDNS22 = None

# Load domain for translation
for module in (gettext, gtk.glade):
  module.bindtextdomain(handlepaths.APP_NAME, handlepaths.getPath('locale'))
  module.textdomain(handlepaths.APP_NAME)

def on_winConnect_delete_event(widget, data=None):
  "Close the main Window and gtk main loop"
  if procDial:
    on_btnConnect_clicked(widget, data)
  gtk.main_quit()

def clearLabels():
  "Empty the value of the labels"
  for widget in (lblInterface2, lblLocalIP2, lblRemoteIP2, lblDNS12, lblDNS22):
    widget.set_label(_('unknown'))
  
def readOutput(fd, data):
  "Read output for connection"
  global procDial

  if procDial:
    # If not yet running
    if procDial.poll() is None:
      # Connecting..
      line = fd.readline()
      if line.startswith('--> Using interface '):
        imgStatus.set_from_icon_name('network-receive', gtk.ICON_SIZE_BUTTON)
        btnConnect.set_label('gtk-disconnect')
        btnConnect.set_sensitive(True)
        lblInterface2.set_label(line[20:-1])
      elif line.startswith('--> local  IP address '):
        lblLocalIP2.set_label(line[22:-1])
      elif line.startswith('--> remote IP address '):
        lblRemoteIP2.set_label(line[22:-1])
      elif line.startswith('--> primary   DNS address '):
        lblDNS12.set_label(line[26:-1])
      elif line.startswith('--> secondary DNS address '):
        lblDNS22.set_label(line[26:-1])
        
      # Add line to the activity log
      if line:
        txtbLog.insert(txtbLog.get_end_iter(), line)
      # Continue iter
      return True
    else:
      # Disconnected
      procDial = None
      txtbLog.insert(txtbLog.get_end_iter(), 'disconnected.\n')
      imgStatus.set_from_icon_name('network-offline', gtk.ICON_SIZE_BUTTON)
      clearLabels()
      btnConnect.set_label('gtk-connect')
      btnConnect.set_sensitive(True)
  # Stop iter
  return False

def on_btnConnect_clicked(widget, data=None):
  "Start or stop internet connection"
  global procDial

  # Is already running?
  if procDial:
    print 'terminating...'
    procDial.terminate()
    btnConnect.set_sensitive(False)
  else:
    print 'connecting...'
    txtbLog.set_text('connecting...\n')
    btnConnect.set_sensitive(False)
    procDial = subprocess.Popen(['wvdial', '-C',
      os.path.join(settings.confdir, '%s.wv' % connectionName), 'BlueDUN'],
      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # Add asynchronous IO watch for stdout and stderr
    stdout_id = glib.io_add_watch(procDial.stdout, glib.IO_IN|glib.IO_HUP, readOutput)
    stderr_id = glib.io_add_watch(procDial.stderr, glib.IO_IN|glib.IO_HUP, readOutput)

def rescroll(adj, scroll):
  "Move scroll to the end"
  adj.set_value(adj.upper-adj.page_size)
  scroll.set_vadjustment(adj)

def showWindow(newConnection):
  "Show connect dialog"
  global connectionName
  global txtbLog
  global btnConnect
  global imgStatus
  global lblConnection2
  global lblInterface2
  global lblLocalIP2
  global lblRemoteIP2
  global lblDNS12
  global lblDNS22

  connectionName = newConnection
  gladeFile = gtk.glade.XML(
    fname=handlepaths.getPath('ui', 'connect.glade'),
    domain=handlepaths.APP_NAME)
  signals = {
    'on_btnConnect_clicked': on_btnConnect_clicked,
    'on_winConnect_delete_event': on_winConnect_delete_event
  }
  gladeFile.signal_autoconnect(signals)
  gw = gladeFile.get_widget

  winConnect = gw('winConnect')
  winConnect.set_icon_from_file(handlepaths.get_app_logo())
  winConnect.set_title(_('Connect / Disconnect'))
  txtvLog = gw('txtvLog')
  txtbLog = txtvLog.get_buffer()
  scrollLog = gw('scrollLog')
  btnConnect = gw('btnConnect')
  imgStatus = gw('imgStatus')
  lblConnection2 = gw('lblConnection2')
  lblInterface2 = gw('lblInterface2')
  lblLocalIP2 = gw('lblLocalIP2')
  lblRemoteIP2 = gw('lblRemoteIP2')
  lblDNS12 = gw('lblDNS12')
  lblDNS22 = gw('lblDNS22')
  clearLabels()
  lblConnection2.set_label(connectionName)

  # Scroll automaticall at the end
  vadj = scrollLog.get_vadjustment()
  vadj.connect('changed', rescroll, scrollLog)

  winConnect.show()
